import { defineStore } from 'pinia'
import { getUrlParam } from 'lj-utils'
import { getReq, postReq } from '@/api/request'
import { useFetch } from '@vueuse/core'

export const useAlbumStore = defineStore('album', {
  state: () => ({
    albumList: [],
    folderList: [],
    mediaList: [],
    albumObj: {},
    nowAlbum: {},
    nowFolder: null,
    nowMediaPage: 0,
    hasMore: true,
    showTipsWatch: false,
  }),
  getters: {
    nowTabObj: (state) => state.tabObj[state.nowKey] || {},
  },
  actions: {
    async getFileUrl(fileId){
      const info = await postReq('/getFileUrl', {
        files:[
          {
            fileId:fileId,
            
          }
        ],
      })
    },
    async uploadOne(file, basePath) {
      const path = basePath.value + '/' + file?.name
      const info = await postReq('/upload2cos', {
        path,
      })
      const result = info?.data || {}
      if (!result?.url) {
        return { status: 'fail', response: { url: '' } }
      }
      const data = new FormData()
      data.append('key', path || file?.name)
      data.append('Signature', result.authorization)
      data.append('x-cos-security-token', result.token)
      data.append('x-cos-meta-fileid', result.cos_file_id)
      data.append('file', file.raw, path)
      // console.error('uploadOne', result)
      const res = await useFetch(result.url, {
        method: 'POST',
        body: data,
      }).json()
      file.fileId = result.file_id
      if (res?.statusCode?.value === 204) {
        return {
          status: 'success',
          response: { url: '', fileId: result.file_id },
        }
      }
      return { status: 'fail', response: { url: '' } }
    },
    setNowAlbum(item) {
      this.nowAlbum = item
      this.getAlbumFolder()
    },
    setNowFolder(item, hideGetFolderDetail = false) {
      this.nowFolder = item
      this.mediaList = []
      this.hasMore = true
      !hideGetFolderDetail && this.getFolderDetail()
    },
    async getFolderDetail(page = 0) {
      const data = {
        groupId: this.nowAlbum.groupId,
        subfolderId: this.nowFolder._id,
        page,
      }
      // console.error(data)
      const res = await getReq('/getSubFolderMediaV3', data)
      if (!page) {
        this.nowMediaPage = 0
        this.hasMore = true
        this.mediaList = []
      }
      const resList = (res.list || []).map((v) => {
        v.count = (v?.videoCnt || 0) + (v?.imgCnt || 0)
        return v
      })
      if (res.isEnd) {
        this.hasMore = false
      } else {
        this.hasMore = true
      }
      this.nowMediaPage++
      this.mediaList = [...this.mediaList, ...resList]
      return
    },
    async getAlbumFolder() {
      if (!this.nowAlbum?.groupId) {
        this.showTipsWatch = true
        return
      }
      const res = await getReq('/getAlbumSubFolderList', {
        groupId: this.nowAlbum.groupId,
      })
      const folderObj = {}
      this.folderList = (res.data || []).map((v) => {
        folderObj[v._id] = v
        v.count = (v?.videoCnt || 0) + (v?.imgCnt || 0)
        return v
      })
      const folderId = getUrlParam('folderId', location.hash)
      // console.error(folderId)
      if (folderId && folderObj[folderId]) {
        this.setNowFolder(folderObj[folderId])
      } else {
        this.setNowFolder(this.folderList?.[0] || {}, true)
      }
      return
    },
    async getAllAlbumGroup() {
      const res = await getReq('/getAllAlbumGroup', {})
      this.albumList = (res.albumList || []).map((v) => {
        v.name = v.creatorName.slice(0, 8) + ' 管理的群相册'
        this.albumObj[v.groupId] = v
        return v
      })
      const urlGroupId = getUrlParam('groupId', location.hash)
      if (urlGroupId && this.albumObj[urlGroupId]) {
        this.setNowAlbum(this.albumObj[urlGroupId])
      } else {
        this.setNowAlbum(this.albumList?.[0] || {})
      }
      return
    },
  },
})
export default useAlbumStore
